<?php

namespace  app\api\controller;

use app\api\controller\ApiBase;

// 需要登录的时候继承！
class AuthBase extends ApiBase
{
    public $userId = null;
    public $username = null;
    public $accessToken = null;

    public function initialize()
    {
        parent::initialize();
        // 获取前端发送过来的请求头的token
        $this->accessToken = $this->request->header('access_token');
        if (!$this->accessToken || !$this->isLogin()) {
            # code...
            /**
             * 这里逻辑跟验证后端管理系统用户是否登录相似，需用到
             *  throw new new HttpResponseException(redirect(...$args));的思路
             */
            return $this->show(config('status.error'), '没有登录');
        }
    }

    // 判断登录
    public function isLogin()
    {
        $userInfo = cache(config('redis.token_pre') . $this->accessToken);
        if (!$userInfo) {
            # code...
            return false;
        }

        // 判断里面redis中是否有值
        if (!empty($userInfo['id']) && !empty($userInfo['username'])) {
            # code...
            $this->userId = $userInfo['id'];
            $this->username = $userInfo['username'];
            return true;
        }

        return false;
    }
}
